<template>
  <s-layout
    title="发布内容"
    navbar="inner"
    :bgStyle="{ color: '#f8f8f8' }"
    v-if="accountInfo.miniProgram.envVersion === 'release'"
  >
    <view class="publish-page">
      <view class="form-container">
        <view class="form-item">
          <view class="label">类型选择</view>
          <scroll-view scroll-x class="type-scroll">
            <view class="type-list">
              <view
                class="type-item"
                :class="{ active: formData.type === type.value }"
                v-for="type in publishTypes"
                :key="type.value"
                @tap="selectType(type.value)"
              >
                <text class="type-icon">{{ type.icon }}</text>
                <text class="type-name">{{ type.name }}</text>
              </view>
            </view>
          </scroll-view>
        </view>

        <view class="form-item">
          <view class="label">标题</view>
          <input
            class="input"
            v-model="formData.title"
            placeholder="请输入标题"
            maxlength="50"
          />
        </view>

        <view class="form-item">
          <view class="label">简介</view>
          <textarea
            class="textarea"
            v-model="formData.synopsis"
            placeholder="请输入简介，简要描述您的内容"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <view class="label">图片</view>
          <view class="media-upload">
            <view class="upload-list">
              <view
                class="upload-item"
                v-for="(pic, index) in uploadedPics"
                :key="index"
              >
                <image :src="pic" class="upload-image" mode="aspectFill" />
                <view class="delete-btn" @tap="deletePic(index)">×</view>
              </view>
              <view
                class="upload-btn"
                @tap="chooseImage"
                v-if="uploadedPics.length < 9"
              >
                <text class="upload-icon">+</text>
                <text class="upload-text">添加图片</text>
              </view>
            </view>
          </view>
        </view>

        <view class="form-item" v-if="formData.type === 3">
          <view class="label">视频</view>
          <view class="video-upload">
            <view v-if="formData.video" class="video-preview">
              <video :src="formData.video" class="video-player" controls />
              <view class="delete-btn" @tap="deleteVideo">×</view>
            </view>
            <view v-else class="upload-btn video-btn" @tap="chooseVideo">
              <text class="upload-icon">📹</text>
              <text class="upload-text">选择视频</text>
            </view>
          </view>
        </view>

        <view class="form-item">
          <view class="label">详细内容</view>
          <textarea
            class="textarea content-textarea"
            v-model="formData.content"
            placeholder="请输入详细内容，分享您的精彩故事..."
            maxlength="2000"
          />
        </view>
      </view>

      <view class="bottom-actions">
        <button class="submit-btn" @tap="submitRelease" :disabled="submitting">
          <text v-if="submitting">发布中...</text>
          <text v-else>立即发布</text>
        </button>
      </view>
    </view>
  </s-layout>
  <s-layout
    title="发布内容"
    navbar="inner"
    :bgStyle="{ color: '#f8f8f8' }"
    v-else
  >
    <view>
      <image
      src="https://img.yzcdn.cn/vant/apple-3.jpg"
      mode="widthFix"
      style="width: 100%;"
      />
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive } from "vue";
import sheep from "@/sheep";
import { baseUrl } from "@/sheep/config";
const accountInfo = uni.getAccountInfoSync();
const publishTypes = ref([
  { value: 2, name: "推荐", icon: "👍" },
  { value: 3, name: "视频", icon: "🎬" },
  { value: 7, name: "文旅", icon: "🏞️" },
]);

const formData = reactive({
  type: 2,
  title: "",
  synopsis: "",
  pics: "",
  video: "",
  content: "",
});

const uploadedPics = ref([]);
const submitting = ref(false);

function selectType(type) {
  formData.type = type;
  if (type !== 3) {
    formData.video = "";
  }
}

async function chooseImage() {
  uni.chooseImage({
    count: 9 - uploadedPics.value.length,
    sizeType: ["compressed"],
    sourceType: ["camera", "album"],
    success: async (res) => {
      for (let filePath of res.tempFilePaths) {
        await uploadFile(filePath, "image");
      }
    },
  });
}

async function chooseVideo() {
  uni.chooseVideo({
    sourceType: ["camera", "album"],
    maxDuration: 60,
    success: async (res) => {
      await uploadFile(res.tempFilePath, "video");
    },
  });
}

async function uploadFile(filePath, type) {
  uni.showLoading({ title: `${type === "image" ? "图片" : "视频"}上传中...` });

  try {
    const result = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: baseUrl + "/h5/file/upload",
        filePath: filePath,
        name: "file",
        header: {
          Authorization: uni.getStorageSync("token"),
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            resolve(data.data);
          } else {
            reject(new Error(data.msg || "上传失败"));
          }
        },
        fail: reject,
      });
    });

    if (type === "image") {
      uploadedPics.value.push(result);
      formData.pics = uploadedPics.value.join(",");
    } else {
      formData.video = result;
    }

    uni.hideLoading();
    uni.showToast({
      title: `${type === "image" ? "图片" : "视频"}上传成功`,
      icon: "success",
    });
  } catch (error) {
    uni.hideLoading();
    uni.showToast({ title: error.message || "上传失败", icon: "none" });
  }
}

function deletePic(index) {
  uploadedPics.value.splice(index, 1);
  formData.pics = uploadedPics.value.join(",");
}

function deleteVideo() {
  formData.video = "";
}

async function submitRelease() {
  if (!validateForm()) return;

  submitting.value = true;

  try {
    const res = await sheep.$api.release.add(formData);
    if (res) {
      uni.showToast({ title: "发布成功", icon: "success" });
      setTimeout(() => {
        sheep.$router.go("/pages/user/my-release");
      }, 1500);
    } else {
      throw new Error("发布失败");
    }
  } catch (error) {
    uni.showToast({ title: error || "发布失败", icon: "none" });
  } finally {
    submitting.value = false;
  }
}

function validateForm() {
  if (!formData.title.trim()) {
    uni.showToast({ title: "请输入标题", icon: "none" });
    return false;
  }
  if (!formData.synopsis.trim()) {
    uni.showToast({ title: "请输入简介", icon: "none" });
    return false;
  }
  if (!formData.content.trim()) {
    uni.showToast({ title: "请输入详细内容", icon: "none" });
    return false;
  }
  if (formData.type === 3 && !formData.video) {
    uni.showToast({ title: "视频类型需要上传视频", icon: "none" });
    return false;
  }
  return true;
}
</script>

<style lang="scss" scoped>
$primary-color: #8b4513;
$secondary-color: #daa520;
$text-dark: #333;
$text-light: #666;
$border-color: #e5e5e5;
$bg-light: #f8f8f8;

.publish-page {
  padding-bottom: 120rpx;
  background: #f8f8f8;
}

.form-container {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 40rpx;

  .label {
    font-size: 28rpx;
    font-weight: 500;
    color: $text-dark;
    margin-bottom: 20rpx;
  }

  .input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    border: 2rpx solid $border-color;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: $text-dark;
    background: white;
  }

  .textarea {
    width: 100%;
    min-height: 120rpx;
    padding: 20rpx;
    border: 2rpx solid $border-color;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: $text-dark;
    background: white;
    box-sizing: border-box;
  }

  .content-textarea {
    min-height: 200rpx;
  }
}

.type-scroll {
  width: 100%;
  white-space: nowrap;
}

.type-list {
  display: flex;
  gap: 20rpx;
  padding: 10rpx 0;
}

.type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 30rpx;
  border: 2rpx solid $border-color;
  border-radius: 16rpx;
  background: white;
  min-width: 120rpx;
  flex-shrink: 0;

  &.active {
    border-color: $primary-color;
    background: rgba(139, 69, 19, 0.05);
  }

  .type-icon {
    font-size: 32rpx;
    margin-bottom: 8rpx;
  }

  .type-name {
    font-size: 24rpx;
    color: $text-dark;
  }
}

.media-upload {
  .upload-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }

  .upload-item {
    position: relative;
    width: 200rpx;
    height: 200rpx;

    .upload-image {
      width: 100%;
      height: 100%;
      border-radius: 12rpx;
    }

    .delete-btn {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      width: 40rpx;
      height: 40rpx;
      background: red;
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }

  .upload-btn {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed $border-color;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: $bg-light;

    .upload-icon {
      font-size: 48rpx;
      color: $text-light;
      margin-bottom: 10rpx;
    }

    .upload-text {
      font-size: 24rpx;
      color: $text-light;
    }
  }
}

.video-upload {
  .video-preview {
    position: relative;

    .video-player {
      width: 100%;
      height: 400rpx;
      border-radius: 12rpx;
    }

    .delete-btn {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      width: 40rpx;
      height: 40rpx;
      background: rgba(0, 0, 0, 0.6);
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }

  .video-btn {
    width: 100%;
    height: 200rpx;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background: white;
  border-top: 2rpx solid $border-color;
  display: flex;
  gap: 20rpx;
  z-index: 100;

  .submit-btn {
    flex: 1;
    height: 80rpx;
    background: linear-gradient(
      90deg,
      $primary-color 0%,
      $secondary-color 100%
    );
    border-radius: 40rpx;
    color: white;
    font-size: 28rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;

    &[disabled] {
      opacity: 0.6;
    }
  }
}
</style>
